package org.jeecg.modules.medication_order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.medication_order.entity.MedicationOrder;
import org.jeecg.modules.medication_order.service.IMedicationOrderService;
import org.jeecg.modules.medication_order.vo.MedicationOrderVo;
import org.jeecg.modules.medication_order.entity.MedicationOrderDetail;
import org.jeecg.modules.medication_order_detail.service.IMedicationOrderDetailService;
import org.jeecg.modules.nurse_user_orders.entity.NurseUserOrders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.ArrayList;
import java.util.UUID;
import java.util.stream.Collectors;

 /**
 * @Description: 药房订单
 * @Author: jeecg-boot
 * @Date:   2025-06-20
 * @Version: V1.0
 */
@Api(tags="药房订单")
@RestController
@RequestMapping("/medication_order/medicationOrder")
@Slf4j
public class MedicationOrderController extends JeecgController<MedicationOrder, IMedicationOrderService> {
	@Autowired
	private IMedicationOrderService medicationOrderService;
	 @Autowired
	 private IMedicationOrderDetailService medicationOrderDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param medicationOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "药房订单-分页列表查询")
	@ApiOperation(value="药房订单-分页列表查询", notes="药房订单-分页列表查询")
	@GetMapping(value = "/list")
	 @PermissionData(pageComponent = "nurse/medication_order/MedicationOrderList")
	public Result<IPage<MedicationOrder>> queryPageList(MedicationOrder medicationOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MedicationOrder> queryWrapper = QueryGenerator.initQueryWrapper(medicationOrder, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<MedicationOrder> page = new Page<MedicationOrder>(pageNo, pageSize);
		IPage<MedicationOrder> pageList = medicationOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param medicationOrder
	 * @return
	 */
	@AutoLog(value = "药房订单-添加")
	@ApiOperation(value="药房订单-添加", notes="药房订单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MedicationOrder medicationOrder) {
		medicationOrderService.save(medicationOrder);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param medicationOrder
	 * @return
	 */
	@AutoLog(value = "药房订单-编辑")
	@ApiOperation(value="药房订单-编辑", notes="药房订单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MedicationOrder medicationOrder) {
		medicationOrderService.updateById(medicationOrder);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "药房订单-通过id删除")
	@ApiOperation(value="药房订单-通过id删除", notes="药房订单-通过id删除")
	@RequiresPermissions("medication_order:medication_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		medicationOrderService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "药房订单-批量删除")
	@ApiOperation(value="药房订单-批量删除", notes="药房订单-批量删除")
	@RequiresPermissions("medication_order:medication_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.medicationOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 复制订单
	 *
	 * @param id  原始订单ID
	 * @param num 复制数量
	 * @return
	 */
	@AutoLog(value = "药房订单-复制订单")
	@ApiOperation(value = "药房订单-复制订单", notes = "药房订单-复制订单")
	@PostMapping(value = "/copyOrder")
	public Result<?> copyOrder(@RequestParam(name = "id") String id, @RequestParam(name = "num") Integer num) {
		try {
			// 检查参数
			if (num <= 0) {
				return Result.error("复制数量必须大于0");
			}

			// 查询原始订单
			QueryWrapper<MedicationOrder> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("id", id);
			MedicationOrder originalOrder = medicationOrderService.getOne(queryWrapper);
			
			if (originalOrder == null) {
				return Result.error("未找到ID为 " + id + " 的订单");
			}

			// 复制订单
			List<MedicationOrder> newOrders = new ArrayList<>();
			List<MedicationOrderDetail> newOrderDetails = new ArrayList<>();

			// 查询原始订单的明细
			QueryWrapper<MedicationOrderDetail> detailQueryWrapper = new QueryWrapper<>();
			detailQueryWrapper.eq("order_id", id);
			List<MedicationOrderDetail> originalOrderDetails = medicationOrderDetailService.list(detailQueryWrapper);

			for (int i = 0; i < num; i++) {
				// 复制主订单
				MedicationOrder newOrder = new MedicationOrder();
				BeanUtils.copyProperties(originalOrder, newOrder);
				
				// 生成新的ID
				String newId = UUID.randomUUID().toString().replace("-", "");
				newOrder.setId(newId);
				
				// 清除创建时间和更新时间相关字段
				newOrder.setCreateTime(new Date());
				newOrder.setUpdateTime(null);
				newOrder.setUpdateBy(null);
				newOrders.add(newOrder);

				// 复制订单明细
				for (MedicationOrderDetail originalDetail : originalOrderDetails) {
					MedicationOrderDetail newDetail = new MedicationOrderDetail();
					BeanUtils.copyProperties(originalDetail, newDetail);
					
					// 设置新的ID和关联的订单ID
					String detailId = UUID.randomUUID().toString().replace("-", "");
					newDetail.setId(detailId);
					newDetail.setOrderId(newId);
					newDetail.setCreateTime(new Date());
					newDetail.setUpdateTime(null);
					newDetail.setUpdateBy(null);
					
					newOrderDetails.add(newDetail);
				}
			}

			// 批量保存新订单和订单明细
			medicationOrderService.saveBatch(newOrders);
			medicationOrderDetailService.saveBatch(newOrderDetails);

			JSONObject result = new JSONObject();
			result.put("copiedCount", newOrders.size());
			List<String> newOrderIds = newOrders.stream().map(MedicationOrder::getId).collect(Collectors.toList());
			newOrderIds.add(id);
			result.put("newOrderIds", newOrderIds);

			return Result.OK("成功复制 " + newOrders.size() + " 个订单", result);
		} catch (Exception e) {
			log.error("复制订单失败: ", e);
			return Result.error("复制订单失败: " + e.getMessage());
		}
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "药房订单-通过id查询")
	@ApiOperation(value="药房订单-通过id查询", notes="药房订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MedicationOrder> queryById(@RequestParam(name="id",required=true) String id) {
		MedicationOrder medicationOrder = medicationOrderService.getById(id);
		if(medicationOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(medicationOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param medicationOrder
    */
    @RequiresPermissions("medication_order:medication_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MedicationOrder medicationOrder) {
        return super.exportXls(request, medicationOrder, MedicationOrder.class, "药房订单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("medication_order:medication_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MedicationOrder.class);
    }

	 /**
	  * 微信用户订单
	  *
	  * @param medicationOrderVo
	  * @return
	  */
	 @AutoLog(value = "药房订单-添加")
	 @ApiOperation(value = "药房订单-添加", notes = "药房订单-添加")
	 @PostMapping(value = "/addByWeChat")
	 public Result<?> addByWeChat(@RequestBody MedicationOrderVo medicationOrderVo,HttpServletRequest req) {
         String org = req.getHeader("sys_org_code");
         String mchId = "A01A03".equals(org.substring(0,6))?"1526566731":"1513682771";
		 medicationOrderVo.setSysOrgCode(org);
		 BaseMap map = medicationOrderService.addByWeChat(medicationOrderVo,mchId);
		 return Result.OK(map);
	 }

	 /**
	  * 微信支付用户订单
	  *
	  * @param outTradeNo
	  * @return
	  */
	 @AutoLog(value = "微信用户订单-支付")
	 @ApiOperation(value = "微信用户订单-支付", notes = "微信用户订单-支付")
	 @PostMapping(value = "/payByWeChat")
	 public Result<?> payByWeChat(@RequestParam(name = "outTradeNo") String outTradeNo) {
		 BaseMap map = medicationOrderService.payByWeChat(outTradeNo);
		 return Result.OK(map);
	 }

	 /**
	  * 微信列表查询
	  *
	  * @param beginDate
	  * @param endDate
	  * @param userId
	  * @return
	  */
	 //@AutoLog(value = "药房订单-微信列表查询")
	 @ApiOperation(value = "药房订单-微信列表查询", notes = "用户订单-微信列表查询")
	 @GetMapping(value = "/listByWeChat")
	 public Result<?> listByWeChat(
			 @RequestParam(name = "beginDate", required = true) String beginDate,
			 @RequestParam(name = "endDate", required = true) String endDate,
			 @RequestParam(name = "userId", required = true) String userId,
			 @RequestParam(name = "status", required = true) String status
	 ) {
		 List<Map<String, Object>> list = medicationOrderService.listByWeChat(beginDate, endDate,  userId, status);
		 return Result.ok(list);
	 }

	 /**
	  * 微信用户订单支付回调
	  *
	  * @param request
	  * @return
	  */
	 @AutoLog(value = "微信用户订单-支付回调")
	 @ApiOperation(value = "微信用户订单-支付回调", notes = "微信用户订单-支付回调")
	 @PostMapping(value = "/payNotify")
	 public Result<?> payNotify(HttpServletRequest request) {
		 medicationOrderService.payNotify(request,"1513682771");
		 return Result.OK();
	 }

	 @AutoLog(value = "微信用户订单-支付回调")
	 @ApiOperation(value = "微信用户订单-支付回调", notes = "微信用户订单-支付回调")
	 @PostMapping(value = "/payNotifyah")
	 public Result<?> payNotifyah(HttpServletRequest request) {
		 medicationOrderService.payNotify(request,"1526566731");
		 return Result.OK();
	 }
	 @AutoLog(value = "微信用户订单-退款")
	 @ApiOperation(value = "微信用户订单-退款", notes = "微信用户订单-退款")
	 @GetMapping(value = "/refund")
	 public Result<?> refund(@RequestParam(name = "outTradeNo") String outTradeNo) {
		 BaseMap map = medicationOrderService.refund(outTradeNo);
		 return Result.OK(map);
	 }
	 @AutoLog(value = "微信用户订单-退费回调")
	 @ApiOperation(value = "微信用户订单-退费回调", notes = "微信用户订单-退费回调")
	 @PostMapping(value = "/refundNotify")
	 public Result<?> refundNotify(HttpServletRequest request) {
		 medicationOrderService.refundNotify(request,"1513682771");
		 return Result.OK();
	 }
	 @AutoLog(value = "微信用户订单-退费回调")
	 @ApiOperation(value = "微信用户订单-退费回调", notes = "微信用户订单-退费回调")
	 @PostMapping(value = "/refundNotifyah")
	 public Result<?> refundNotifyah(HttpServletRequest request) {
		 medicationOrderService.refundNotify(request,"1526566731");
		 return Result.OK();
	 }

	 //@AutoLog(value = "药房订单详情通过主表ID查询")
	 @ApiOperation(value="药房订单详情主表ID查询", notes="药房订单详情-通主表ID查询")
	 @GetMapping(value = "/queryMedicationOrderDetailByMainId")
	 public Result<List<MedicationOrderDetail>> queryMedicationOrderDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<MedicationOrderDetail> medicationOrderDetailList = medicationOrderDetailService.selectByMainId(id);
		 return Result.OK(medicationOrderDetailList);
	 }
 }